const { con, ResData } = require('./common');

async function getTasks(userId) {
  const sql = `select * from tasks where user_id = ${userId} order by id desc`,
        res = new ResData();

  const  [rows] = await con.execute(sql);
  res.data = rows;

  return res;
}

async function addTask(content, folderId, userId) {
  const sql = `insert into tasks(content, folder_id, user_id) values ("${content}", ${folderId}, ${userId})`,
        res = new ResData();

  try {
    const [rows] = await con.execute(sql);
    res.data = rows.insertId;
    res.msg = rows.affectedRows === 1 ? '添加成功': '添加失败';
    return res;
  } catch(e) {
    res.code = 401001;
    res.msg  = '添加失败';
    return res;
  }
}

async function updateTaskContentByID(id, content, userId) {
  const sql = `update tasks set content = "${content}" where id = ${id} and user_id = ${userId}`;

  return await updateTaskByID(sql);
}

async function updateTaskFolderByID(id, folderId, userId) {
  let sql = '';

  if(Number(folderId) === 0) { // task not belong any folder
    sql = `update tasks set folder_id = null where id = ${id} and user_id = ${userId}`;
  } else {
    sql = `update tasks set folder_id = "${folderId}" where id = ${id} and user_id = ${userId}`;
  }

  return await updateTaskByID(sql);
}

async function recycleTaskByID(id, userId) {
  const sql = `update tasks set deletedTime = null where user_id = ${userId} and id = ${id}`;

  return await updateTaskByID(sql);
}

async function updateTaskByID(sql) {
  const res = new ResData();

  try {
    const [rows] = await con.execute(sql);
    res.msg = rows.affectedRows === 1 ? '修改成功': '修改失败';
    return res;
  } catch(e) {
    res.code = 401002;
    res.msg  = '修改失败';
    return res;
  }
}

async function deleteTaskByID(id, userId, permanent) {
  let sql = '';
  if(permanent) {
    sql = `delete from tasks where user_id = ${userId} and id = ${id}`;
  } else {
    sql = `update tasks set deletedTime = now() where user_id = ${userId} and id = ${id}`;
  }

  const res = new ResData();

  try {
    const [rows] = await con.execute(sql);
    res.msg  = rows.affectedRows === 1 ? '删除成功' : '删除的对象不存在';
    return res;
  } catch(e) {
    res.code = 401003;
    res.msg  = '删除失败';
    return res;
  }
}

module.exports = {
  getTasks,
  addTask,
  recycleTaskByID,
  updateTaskContentByID,
  updateTaskFolderByID,
  deleteTaskByID
};
